<template>
  <div class="project-settlement">
    <el-form ref="form" :model="searchObj">
      <div class="params-form params-form-gray">
        <el-form-item label="客户名称">
          <el-input v-model="searchObj.customerName" placeholder="请输入客户名称/小区名称" />
        </el-form-item>
        <el-form-item label="负责人">
          <el-input v-model="searchObj.chargePerson" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="承包人">
          <el-input v-model="searchObj.contractor" placeholder="请输入承包人" />
        </el-form-item>
        <el-form-item label="合同编号">
          <el-input v-model="searchObj.contractNo" placeholder="请输入合同编号" />
        </el-form-item>
        <el-form-item>
          <el-button :icon="Search" type="primary" @click="initTableList">查询</el-button>
          <el-button :icon="RefreshRight" plain type="primary" style="background: #ffffff !important" @click="resetTableList"
            >重置
          </el-button>
        </el-form-item>
      </div>
    </el-form>
    <!--    start tab-content-->
    <div class="tab-content">
      <el-tabs v-model="tabActive" @tab-change="initTableList">
        <el-tab-pane v-for="(item, index) in tabList" :label="item" :name="index" />
      </el-tabs>
    </div>
    <!--    end tab-content-->
    <!--    start action-button-->
    <div class="action-button">
      <el-button type="primary" plain @click="exportData" :loading="exportLoading">{{
        exportLoading ? "正在导出" : "按查询条件导出"
      }}</el-button>
    </div>
    <!--    end action-button-->
    <!--     start table-content + pagination -->
    <div class="table-content" v-loading="tableLoading">
      <el-table :data="tableData" style="width: 100%" height="calc(100vh - 500px)">
        <el-table-column prop="customerName" label="客户" min-width="150" />
        <el-table-column prop="customerAddress" label="小区名称" min-width="180" />
        <el-table-column prop="contractTypeName" label="合同类型" min-width="150" />
        <el-table-column prop="contractNo" label="合同编号" min-width="180" />
        <el-table-column prop="signingTime" label="签约日期" min-width="180" />
        <el-table-column label="负责人" show-overflow-tooltip min-width="230">
          <template #default="{ row }">
            <el-popover placement="top" :width="200" trigger="hover">
              <template #reference>
                <span style="cursor: pointer">{{ row.responsiblePerson }}</span>
              </template>
              <div class="charge-person-list">
                <div class="charge-person-item" v-for="item in row.responsiblePersonDetails" :key="item.userId">
                  {{ item.roleName }}:
                  <span class="person-name" style="color: #000">{{ item.username }}</span>
                </div>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="contractorPerson" label="承包人" min-width="120" />
        <el-table-column label="合同金额" prop="totalAmount" min-width="120" :formatter="formatPrice" />
        <el-table-column label="增减项金额" min-width="120" prop="addSubAmount" :formatter="formatPrice" />
        <el-table-column label="整改金额" prop="abarbeitungAmount" min-width="120" :formatter="formatPrice" />
        <el-table-column label="已收款金额" min-width="120" prop="allTotalAmount" :formatter="formatPrice" />
        <el-table-column label="主材成本金额" min-width="150" prop="ingredientAmount" :formatter="formatPrice">
          <template #header>
            <popover-desc title="主材成本金额" content="合同关联主材的锁库出库库存成本和采购成本之和"></popover-desc>
          </template>
        </el-table-column>
        <el-table-column label="辅材成本金额" min-width="150" prop="materialAmount" :formatter="formatPrice">
          <template #header>
            <popover-desc title="辅材成本金额" content="合同关联辅材的锁库出库库存成本和采购成本之和"></popover-desc>
          </template>
        </el-table-column>
        <el-table-column label="人工成本金额" min-width="150" prop="receivedLaborAmount" :formatter="formatPrice">
          <template #header>
            <popover-desc title="人工成本金额" content="合同关联的请款单（是否发包为不发包）的请款金额之和"></popover-desc>
          </template>
        </el-table-column>
        <el-table-column label="发包金额" min-width="150" prop="contracteesAmount" :formatter="formatPrice">
          <template #header>
            <popover-desc title="发包金额" content="若合同存在发包，则取值为合同关联发包管理的发包金额"></popover-desc>
          </template>
        </el-table-column>
        <el-table-column label="已领人工款项" min-width="150" prop="receivedContractLaborAmount" :formatter="formatPrice">
          <template #header>
            <popover-desc title="已领人工款项" content="合同关联的请款单（是否发包为发包）的请款金额之和"></popover-desc>
          </template>
        </el-table-column>
        <el-table-column label="已下辅料款项" min-width="150" prop="receivedMaterialAmount" :formatter="formatPrice">
          <template #header>
            <popover-desc title="已下辅料款项" content="合同订单中已发包辅材商品的发包价*出库数量之和"></popover-desc>
          </template>
        </el-table-column>
        <el-table-column label="已下主材款项" min-width="150" prop="receivedIngredientAmount" :formatter="formatPrice">
          <template #header>
            <popover-desc title="已下主材款项" content="合同订单中已发包主材商品的发包价*出库数量之和"></popover-desc>
          </template>
        </el-table-column>
        <el-table-column label="结算转质保金/押金" min-width="200" prop="settlePledgeDepositMoney" :formatter="formatPrice">
          <template #header>
            <popover-desc title="结算转质保金/押金" content="申请结算录入的质保金和押金之和"></popover-desc>
          </template>
        </el-table-column>
        <el-table-column label="剩余发包金额" min-width="150" prop="remainingContractAmount" :formatter="formatPrice">
          <template #header>
            <popover-desc
              title="剩余发包金额"
              content="发包金额-已领人工款项-已下辅料款项-已下主材款项-结算转质保金/押金"
            ></popover-desc>
          </template>
        </el-table-column>
        <el-table-column label="明责金额" min-width="150" prop="blameAmount" :formatter="formatPrice">
          <template #header>
            <popover-desc title="明责金额" content="合同关联的已核实状态的判责单的判责金额之和（公司承担除外）"></popover-desc>
          </template>
        </el-table-column>
        <el-table-column label="公司明责金额" min-width="150" prop="companyBlameAmount" :formatter="formatPrice">
          <template #header>
            <popover-desc title="公司明责金额" content="合同关联的已核实状态的判责单的判责金额之和（仅公司承担）"></popover-desc>
          </template>
        </el-table-column>
        <el-table-column label="质保金" min-width="150" prop="depositAmount" :formatter="formatPrice">
          <template #header>
            <popover-desc title="质保金" content="合同关联的请款单转质保金的金额合计+申请结算录入的质保金合计的和"></popover-desc>
          </template>
        </el-table-column>
        <el-table-column label="押金" min-width="150" prop="pledgeAmount" :formatter="formatPrice">
          <template #header>
            <popover-desc title="押金" content="合同关联的请款单转押金的金额合计+申请结算录入的押金合计的和"></popover-desc>
          </template>
        </el-table-column>
        <el-table-column label="其他款项" min-width="150" prop="otherMoney" :formatter="formatPrice">
          <template #header>
            <popover-desc title="其他款项" content="合同关联的报销单金额之和"></popover-desc>
          </template>
        </el-table-column>
        <el-table-column label="利润比" min-width="150">
          <template #default="{ row }"> {{ row.profitRatio }}% </template>
          <template #header>
            <popover-desc
              title="利润比"
              content="1-（发包金额+主材成本金额+辅材成本金额+人工成本金额+公司承担明责金额）/（合同金额+增减项金额+整改金额）"
            ></popover-desc>
          </template>
        </el-table-column>
        <el-table-column label="状态" min-width="120">
          <template #default="{ row }">
            <span
              class="status-tag"
              :style="{
                background: settleStatusObj[row.settleStatus]?.bgColor,
                color: settleStatusObj[row.settleStatus]?.color
              }"
              >{{ settleStatusObj[row.settleStatus]?.text }}</span
            >
          </template>
        </el-table-column>
        <el-table-column prop="settleApplyTime" label="创建时间" min-width="200" />
        <el-table-column prop="createBy" label="创建人" min-width="120" />
        <el-table-column label="操作" fixed="right" width="140">
          <template #default="{ row }">
            <el-button
              type="primary"
              v-if="['wait_settle', 'settle_not_pass'].includes(row.settleStatus)"
              link
              size="small"
              @click="handleApplySettlement(row)"
              >申请结算</el-button
            >
            <el-button type="primary" link size="small" @click="openAudit(row)" v-if="row.flowInstanceId">审批记录</el-button>
            <el-button type="primary" link size="small" @click="withDrawApproval(row)" v-if="row.settleStatus == 'settle_ing'"
              >撤回审批</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pageInfo.current"
        v-model:page-size="pageInfo.size"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!--    end table-content + pagination-->
  </div>
  <!--  start apply-settlement-->
  <apply-settlement
    v-model="showApplySettlement"
    @handleApplySave="initTableList"
    v-if="showApplySettlement"
    :contractId="currentContractId"
  ></apply-settlement>
  <!--  end  start apply-settlement-->
  <!--    start 审批记录-->
  <Audit v-model:show="visibleAudit" v-if="visibleAudit" :code="code" />
  <!--    end 审批记录-->
</template>

<script setup>
import { getCurrentInstance, ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { RefreshRight, Search } from "@element-plus/icons-vue";
import PopoverDesc from "./components/PopoverDesc.vue";
import ApplySettlement from "./components/ApplySettlement.vue";
import { settleList, exportRecord, cancelProcess } from "@/apis/settlementManagement";
import exportExcel from "@/utils/exportExcel";
import Audit from "@/views/audit/index.vue";

const route = useRoute();

const contractNo = route.query?.contractNo ?? "";

const { proxy } = getCurrentInstance();

//搜索
const searchObj = ref({ customerName: "", chargePerson: "", contractor: "", contractNo: "" });
const resetTableList = () => {
  searchObj.value = {
    customerName: "",
    chargePerson: "",
    contractor: "",
    settleStatus: "",
    contractNo: ""
  };
  initTableList();
};

//tab
const tabActive = ref(0);
const tabList = ["全部", "待申请", "结算中", "未通过", "已结算"];
const settleStatusTabParam = {
  0: "",
  1: "wait_settle",
  2: "settle_ing",
  3: "settle_not_pass",
  4: "settle"
};

//分页
const total = ref(0);
const pageInfo = ref({
  current: 1,
  size: 10
});
const handleSizeChange = val => {
  pageInfo.value.size = val;
  getTableList();
};
const handleCurrentChange = val => {
  pageInfo.value.current = val;
  getTableList();
};

//表格
const settleStatusObj = {
  wait_settle: { bgColor: "#FFF0D9", color: "#FF9900", text: "待申请" },
  settle: { bgColor: "#E3F9E9", color: "#14C85C", text: "已结算" },
  settle_ing: { bgColor: "#D9EDFF", color: "#007DFF", text: "结算中" },
  settle_not_pass: { bgColor: "#FFE1E1", color: "#F53F3F", text: "未通过" }
};
const tableLoading = ref(false);
const tableData = ref([]);
const getTableList = async () => {
  tableLoading.value = true;
  let params = {
    customer: searchObj.value.customerName,
    contractorPerson: searchObj.value.contractor,
    responsiblePerson: searchObj.value.chargePerson,
    contractNo: searchObj.value.contractNo,
    settleStatus: settleStatusTabParam[tabActive.value]
  };
  const { data } = await settleList(pageInfo.value, params);
  tableData.value = data.list ?? [];
  total.value = data.total ?? 0;
  tableLoading.value = false;
};
const initTableList = () => {
  pageInfo.value.current = 1;
  getTableList();
};
const formatPrice = (row, column, cellValue) => {
  return `￥${cellValue}`;
};

//审批记录
const visibleAudit = ref(false);
const code = ref("");
const openAudit = data => {
  code.value = data.flowInstanceId;
  visibleAudit.value = true;
};

//申请结算
const currentContractId = ref("");
const showApplySettlement = ref(false);
const handleApplySettlement = row => {
  currentContractId.value = row.contractId;
  showApplySettlement.value = true;
};

//撤回审批
const withDrawApproval = row => {
  proxy.$modal
    .confirm("确定要撤回审批吗")
    .then(async () => {
      await cancelProcess(row.contractId);
      proxy.$modal.msgSuccess("操作成功");
      initTableList();
    })
    .catch(() => {});
};

//导出
const exportLoading = ref(false);
const exportData = async () => {
  let params = {
    customer: searchObj.value.customerName,
    contractorPerson: searchObj.value.contractor,
    responsiblePerson: searchObj.value.chargePerson,
    contractNo: searchObj.value.contractNo,
    settleStatus: settleStatusTabParam[tabActive.value]
  };
  exportLoading.value = true;
  const res = await exportRecord(params);
  exportExcel(res, "结算管理");
  exportLoading.value = false;
};

onMounted(() => {
  searchObj.value.contractNo = contractNo;
  getTableList();
});
</script>

<style lang="scss" scoped>
@import "@/assets/styles/index.scss";

.project-settlement {
  height: 100%;
  display: flex;
  flex-direction: column;
  //params-form
  .params-form {
    display: flex;
    justify-content: space-between;
    box-sizing: border-box;
    flex-wrap: wrap;
    margin: 20px;
    :deep(.el-form-item) {
      width: calc(33% - 60px);
      margin-right: 60px;
      &:last-child .el-form-item__content {
        justify-content: flex-end;
      }
      &:nth-of-type(3n),
      &:last-child {
        margin-right: 0;
      }
    }
  }

  //tab-content
  .tab-content {
    :deep(.el-tabs__nav-scroll) {
      padding-left: 20px;
    }

    :deep(.el-tabs__nav-wrap:after) {
      height: 1px;
      transform: scaleX(1.5);
    }
  }

  //action-button
  .action-button {
    padding: 0 20px;
    margin-bottom: 10px;
  }

  //table-content
  //表格样式
  .table-content {
    margin: 0 20px 20px 20px;
    box-sizing: border-box;

    :deep(.el-table) {
      border: 1px solid #dcdfe6;

      tr {
        height: 45px;
      }

      tr th {
        background: #f2f6fc;
        font-weight: normal;
        font-size: 14px;
        color: #909399;
      }

      tr td {
        color: #606266;
      }

      tr:nth-of-type(even) td {
        background: #f5f7fa;
      }
    }

    .status-tag {
      @include blockStyle(56px, 20px, #dcdfe6, 2px);
      border: 1px solid #ffffff;
      display: inline-block;
      @include flexStyle(center, center);
      font-size: 12px;
    }

    .charge-person-list {
      .charge-person-item {
        @include fontStyle(12px, #86909c);
        margin-bottom: 10px;
      }
    }
  }

  :deep(.el-pagination) {
    margin: 20px;
    justify-content: flex-end;
  }
}
</style>
